package com.sino.operation.service.basic;

import com.sino.operation.service.impl.BizTaskReleaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Title: ReleaseCacheService
 * @Description: 流程完成或终止后，释放缓存中的数据
 * @Author dengls
 * @date 2021/10/25 15:25
 */
@Service
public class ReleaseCacheService {

    @Autowired
    private BizTaskReleaseServiceImpl releaseService;

    public void release(String journalNo) {
        this.releaseTaskMap(journalNo);
        this.releaseTaskService(journalNo);
    }

    /**
     * 释放推送任务中的缓存Map
     *
     * @param journalNo
     */
    private void releaseTaskMap(String journalNo) {
        List<String> keyList = this.parseKeyListForFilter(WorkFlowService.TaskHashMap, journalNo);
        keyList.forEach(
                item -> {
                    if (WorkFlowService.TaskHashMap.containsKey(item)) {
                        //按照常理来说，这边应该是不用判断key值是否存在的，因为本来就是通过流水号去模糊匹配出来的，以防万一，万一其它线程刚好终止啥的
                        WorkFlowService.TaskHashMap.remove(item);
                    }
                }
        );
    }

    /**
     * 清除释放任务表中的缓存
     *
     * @param journalNo
     */
    private void releaseTaskService(String journalNo) {
        releaseService.releaseTask(journalNo);
    }


    private List<String> parseKeyListForFilter(Map<String, String> map, String filters) {
        if (map == null) {
            return null;
        } else {
            return map.entrySet().stream()
                    .filter((e) -> checkKey(e.getKey(), filters))
                    .map(item -> item.getKey())
                    .collect(Collectors.toList()
                    );
        }
    }

    /**
     * 通过indexOf匹配想要查询的字符
     */
    private static boolean checkKey(String key, String filters) {
        if (key.indexOf(filters) > -1) {
            return true;
        } else {
            return false;
        }
    }
}
